// import { baseUrl } from './request/doRequest';
import md5 from 'blueimp-md5'
import authority from './authority'
import uploadToken from '@/api/uploadToken'

async function getToken() {
  console.log(1)
  // eslint-disable-next-line
  const name = md5(Date.now()) + '.png' // todo
  // console.log(name)
  const {
    accessid,
    callback,
    dir,
    host,
    policy,
    signature
  } = await uploadToken()
  // const {accessid, callback, host, policy, signature} = await aliToken()
  // fd['key'] = `${dir}${md5(file.name)}${file.name.substr(file.name.indexOf('.'))}`
  const fd = {
    key: `${dir}${name}`,
    OSSAccessKeyId: accessid,
    policy,
    Signature: signature,
    callback
  }
  // fd[''] = ;
  // // console.log(fd, '123')
  // fd[''] = ;
  // fd[''] = policy;
  // fd[''] = ;
  // fd[''] = callback;
  return { fd, host }
}

async function toUpload(filePath) {
  const { token } = authority.get() || {}
  console.log(token)
  const { fd, host } = await getToken()

  const Authorization = token ? `Bearer ${token}` : ''

  return new Promise((resolve, reject) => {
    wx.showLoading()
    wx.uploadFile({
      url: host,
      filePath,
      name: 'file',
      formData: fd,
      header: {
        Authorization
      },
      success(res) {
        // todo
        if (res.statusCode === 200) {
          resolve(res.data)
          wx.hideLoading()
        } else {
        }
      },
      fail(e) {
        reject(e)
        wx.hideLoading()
      }
    })
  })
}

export function singleUpload() {
  return new Promise((resolve, reject) => {
    wx.chooseImage({
      count: 1,
      success: ({ tempFilePaths }) => {
        const [filePath] = tempFilePaths
        console.log(filePath, 8888)
        toUpload(filePath)
          .then(resolve)
          .catch(reject)
      },
      fail(e) {
        reject(e)
      }
    })
  })
}
